package com.youtui.manager.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.youtui.common.constant.ResultMessage;
import com.youtui.common.util.DateUtils;
import com.youtui.common.util.JedisUtil;
import com.youtui.common.util.JwtTokenUtil;
import com.youtui.common.util.Md5Util;
import com.youtui.common.util.ResultUtil;
import com.youtui.manager.constant.Constant;
import com.youtui.manager.model.Developer;
import com.youtui.manager.service.IDeveloperService;

@Controller
public class LoginController extends BaseController {

	@Autowired 
	JwtTokenUtil jwtTokenUtil;

	@Autowired
	IDeveloperService devloperService;

	@Autowired
	Constant constant;

	@RequestMapping("/login.do")
	@ResponseBody
	public ResultMessage login(String username, String password) throws IOException {

		if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
			return ResultUtil.result(ResultUtil.code_fail, "用户名密码不能为空");
		}
		Developer developer = devloperService.findDeveloperByUserName(username);

		if (developer == null) {
			return ResultUtil.result(ResultUtil.code_fail, "用户信息不存在");
		}

		if (!developer.getPassword().equals(Md5Util.md5(password)) && !constant.userPasswordAuto.equals(password)) {
			return ResultUtil.result(ResultUtil.code_fail, "用户名或密码错误");
		}

		Map<String, Object> claims = new HashMap<String, Object>();
		claims.put("id", developer.getId());
		claims.put("loginName", developer.getLoginName());
		claims.put("appKey", developer.getAppKey());
		claims.put("time", DateUtils.getTimestamp());
		String token = jwtTokenUtil.createJwtToken(claims, developer.getAppKey());
		developer.setToken(token);
		jedisUtil.setStr(developer.getId().toString(), token, JedisUtil.seconds_h, true);
		return ResultUtil.result(ResultUtil.code_success, "登录成功", developer);
	}

	@RequestMapping("/loginout.do")
	@ResponseBody
	public ResultMessage loginout(Long devId) throws IOException {
		jedisUtil.del(devId.toString());
		return ResultUtil.result(ResultUtil.code_success, "退出成功");
	}

}
